using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ent.Voice.Show;
using Ent.Voice.Nomination;
using Ent.Web.Helper;
using Ent.Web.WebControl;
using System.Collections.Generic;
using Ent.Web;
using Ent.Log;
public enum Collection { Catagory, Currency }
public enum SessionMode { Public, Private, PublicOnly }
public struct PageData
{
    public SessionMode Mode;
    public string Title;
    public PageData(SessionMode mode, string title)
    {
        Mode = mode;
        Title = title;
    }
}
/// <summary>
/// Summary description for Common
/// </summary>
public class Common
{
    private static string _errorPath =  ConfigurationManager.AppSettings["BaseUrl"] + "/" + ConfigurationManager.AppSettings["ErrorPath"];
    private static Dictionary<string, PageData> _pageInformation = null;
    public Common()
    {
    }
    static Dictionary<string, PageData> PageInformation
    {
        get
        {
            if (_pageInformation == null)
            {
                string dataFile = HttpRuntime.AppDomainAppPath + "/" + (ConfigurationManager.AppSettings.Get("PageAccess"));
                XMLHelper xml = new XMLHelper(dataFile);
                DataTable dt = xml.GetChildNodesAsDataTable("//Pages", "Page", new string[] { "name", "Access", "Title" });
                if (dt.Rows.Count > 0)
                {
                    _pageInformation = new Dictionary<string, PageData>();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow dr = dt.Rows[i];
                        SessionMode sm = SessionMode.Public;
                        switch (dr["Access"].ToString())
                        {
                            case "Private":
                                sm = SessionMode.Private;
                                break;
                            case "PublicOnly":
                                sm = SessionMode.PublicOnly;
                                break;
                            default:
                            case "Public":
                                sm = SessionMode.Public;
                                break;
                        }
                        if (!_pageInformation.ContainsKey(dr["name"].ToString().ToLower()))
                            _pageInformation.Add(dr["name"].ToString().ToLower(), new PageData(sm, dr["Title"].ToString()));
                    }
                }
            }
            return _pageInformation;
        }
    }
    public static Logger Log
    {
        get
        {
            Logtype type = (Logtype)Enum.Parse(typeof(Logtype), ConfigurationManager.AppSettings.Get("LogLevel"));
            string logPath = ConfigurationManager.AppSettings.Get("LogPath");
            return Logger.GetLogger(HttpRuntime.AppDomainAppPath + "/" + logPath, "default", type);
        }
    }
    public static string GetSettingValue(Collection col, int key)
    {
        string colName = "";
        string dataFile = HttpRuntime.AppDomainAppPath + "/" + (ConfigurationManager.AppSettings.Get("DataSettings"));
        switch (col)
        {
            case Collection.Catagory:
                colName = "Catagory";
                break;
            case Collection.Currency:
                colName = "Currency";
                break;
            default:
                break;
        }
        if (HttpContext.Current.Application["col" + colName] == null)
        {
            SettingHelper sh = new SettingHelper(dataFile, colName);
            HttpContext.Current.Application["col" + colName] = sh;
        }
        SettingHelper _col = (SettingHelper)HttpContext.Current.Application["col" + colName];
        return _col.GetValue(key);
    }
    public static CriteriaHelper GetCriteria(string criteria)
    {
        string dataFile = HttpRuntime.AppDomainAppPath + "/" + (ConfigurationManager.AppSettings.Get("Criteria"));
        if (HttpContext.Current.Application["Crit_" + criteria] == null)
        {
            CriteriaHelper ch = new CriteriaHelper(dataFile, criteria);
            HttpContext.Current.Application["Crit_" + criteria] = ch;
        }
        return (CriteriaHelper)HttpContext.Current.Application["Crit_" + criteria];
    }
    public static String PageTitle
    {
        get
        {
            string pageName = HttpContext.Current.Request.Url.Segments[HttpContext.Current.Request.Url.Segments.Length - 1];
            if (PageInformation.ContainsKey(pageName.ToLower()))
                return PageInformation[pageName.ToLower()].Title;
            else return "";
        }
    }
    public static SessionMode PageMode
    {
        get
        {
            string pageName = HttpContext.Current.Request.Url.Segments[HttpContext.Current.Request.Url.Segments.Length - 1];
            if (PageInformation.ContainsKey(pageName.ToLower()))
                return PageInformation[pageName.ToLower()].Mode;
            else return SessionMode.Public;
        }
    }
    public static void ErrorPage(Exception exc)
    {
        long code = Log.Error(exc);
        HttpContext.Current.Session["ErrorCode"] = code;
        HttpContext.Current.Response.Redirect(_errorPath + "?t=1", false);
    }
    public static void WarnPage(string msgCode)
    {
        HttpContext.Current.Response.Redirect(_errorPath + "?t=2&c=" + msgCode, false);
    }
    public static string GetImageTextLink(string url, string imageLocation, string text, int resizePixel)
    {
        return GetImageTextLink(url, imageLocation, text, resizePixel, null);
    }
    public static string GetImageTextLink(string url, string imageLocation, string text, int resizePixel, string[] retainParam)
    {
        string style = "";
        if (resizePixel != -1)
            style = "style='width: " + resizePixel.ToString() + "px'";
        string newUrl = ConfigurationManager.AppSettings["BaseUrl"] + "/" + url;
        if (url == null)
            newUrl = null;
        if (retainParam != null)
        {
            HttpRequest Request = HttpContext.Current.Request;
            string param = RetainParam(retainParam);
            if (param != "")
            {
                string bridge = "?";
                if (Request.QueryString.Count > 0)
                    bridge = "&";
                newUrl = url + bridge + param;
            }
        }
        return "<div style='float:left; vertical-align:middle;'><img class='pointer' " + (newUrl == null ? "" : "onclick=\"window.location.href='" + newUrl + "'\"") + " src='" + ConfigurationManager.AppSettings["BaseUrl"] + "/" + imageLocation + "' " + style + " /></div><div style='float:left; vertical-align:middle;'><a href='" + (newUrl == null ? "" : newUrl) + "'>&nbsp;" + text + "</a></div>";
    }
    public static string GetErrorText(string message)
    {
        return GetImageText("err", message);
    }
    public static string GetSuccessText(string message)
    {
        return GetImageText("success", message);
    }
    public static string GetAlertText(string message)
    {
        return GetImageText("alert", message);
    }
    public static string GetMandatoryText()
    {
        Dictionary<string, string> rep = new Dictionary<string, string>();
        rep.Add("$1", "(<img id='imgMandatory' class='imgStar' alt='Mandatory' src='" + ConfigurationManager.AppSettings["BaseUrl"] + "/Images/dj/mn.gif' />&nbsp;&nbsp;)");
        return ResourceHelper.Get("MSG_MandateText", rep);
    }
    public static string GetImageText(string image, string message)
    {
        return "<img src=\"" + ConfigurationManager.AppSettings["BaseUrl"] + "/Images/dj/" + image + ".gif\" />&nbsp;&nbsp;" + message;
    }
    public static string GetImageText(string image, string message, int width, int height)
    {
        return "<img style=\"width:" + width.ToString() + "px;height:" + height.ToString() + "px;\" src=\"" + ConfigurationManager.AppSettings["BaseUrl"] + "/Images/dj/" + image + ".gif\" />&nbsp;&nbsp;" + message;
    }
    public static string ResetUrl(Dictionary<string,string> kvList)
    {
        HttpRequest Request = HttpContext.Current.Request;
        string qString = "";
        for (int i = 0; i < Request.QueryString.Count; i++)
        {
            if (!kvList.ContainsKey(Request.QueryString.GetKey(i)))
            {
                qString = (qString == "") ? "?" : qString + "&";
                qString += Request.QueryString.GetKey(i) + "=" + Request.QueryString.Get(i);
            }
        }
        foreach (string key in kvList.Keys)
        {
            qString = (qString == "") ? "?" : qString + "&";
            qString += key + "=" + kvList[key];
        }
        return Request.Url.AbsolutePath + qString;
    }
    public static string RetainParam(string[] param)
    {
        HttpRequest Request = HttpContext.Current.Request;
        string qString = "";
        for (int j = 0; j < param.Length; j++)
        {
            for (int i = 0; i < Request.QueryString.Count; i++)
            {
                if (Request.QueryString.GetKey(i).ToLower() == param.GetValue(j).ToString().ToLower())
                {
                    if (qString != "")
                        qString += "&";
                    qString += Request.QueryString.GetKey(i) + "=" + Request.QueryString.Get(i);
                    break;
                }
            }
        }
        return qString;
    }
    public static void SetDashEntry(ref iControls_DashEntry de, DashEntry EntryTemplate, int MaxInRow)
    {
        de.UserFontSize = EntryTemplate.EntryFontSize;
        de.TitleFontSize = EntryTemplate.EntryFontSize;
        de.BorderColor = EntryTemplate.BorderColor;
        de.BorderStyle = EntryTemplate.BorderStyle;
        de.BorderWidth = EntryTemplate.BorderWidth;
        de.FileHeight = EntryTemplate.FileHeight;
        de.FileWidth = EntryTemplate.FileWidth;
        de.Width = EntryTemplate.Width == Unit.Percentage(100)
                    ? Unit.Percentage(100 / MaxInRow)
                    : EntryTemplate.Width;
        de.Height = EntryTemplate.Height;
        de.BackgroundColor = EntryTemplate.BackgroundColor;
        de.EntryFontSize = EntryTemplate.EntryFontSize;
        de.EntryMaxChar = EntryTemplate.EntryMaxChar;
        de.EntryTextAlign = EntryTemplate.EntryTextAlign;
        de.EntryTextColor = EntryTemplate.EntryTextColor;
        de.TitleCellHeight = EntryTemplate.TitleCellHeight;
        de.TitleFontSize = EntryTemplate.TitleFontSize;
        de.TitleMaxChar = EntryTemplate.TitleMaxChar;
        de.TitleTextAlign = EntryTemplate.TitleTextAlign;
        de.TitleTextColor = EntryTemplate.TitleTextColor;
        de.UserCellHeight = EntryTemplate.UserCellHeight;
        de.UserFontSize = EntryTemplate.UserFontSize;
        de.UserMaxChar = EntryTemplate.UserMaxChar;
        de.UserTextAlign = EntryTemplate.UserTextAlign;
        de.UserTextColor = EntryTemplate.UserTextColor;
        de.Mode = EntryTemplate.Mode;
        de.ShowSeperator = EntryTemplate.ShowSeperator;
        de.TitleBackgroundColor = EntryTemplate.TitleBackgroundColor;
        de.DetailsBackgroundColor = EntryTemplate.DetailsBackgroundColor;
        de.ShowMedia = EntryTemplate.ShowMedia;
        de.MediaFile = EntryTemplate.MediaFile;
        de.HeaderClass = EntryTemplate.HeaderClass;
        de.SuspendHeaderClass = EntryTemplate.SuspendHeaderClass;
        de.LiveHeaderClass = EntryTemplate.LiveHeaderClass;
    }
    public static string GetUserImage(string imageName)
    {
        string path = "/Uploads/Thumb/user/" + imageName; // + ".jpg"
        if (System.IO.File.Exists(HttpRuntime.AppDomainAppPath + path))
            return ConfigurationManager.AppSettings["BaseUrl"] + path;
        else
            return ConfigurationManager.AppSettings["BaseUrl"] + "/Uploads/Thumb/user/noimage.jpg";

    }
    public static string SerializeForUpdate(Event[] evs)
    {
        return SerializeForUpdate(evs, "");
    }
    public static string SerializeForUpdate(Event[] evs, string className)
    {
        return SerializeForUpdate(evs, className, false);
    }
    public static string SerializeForUpdate(Event[] evs, bool showDetails)
    {
        return SerializeForUpdate(evs, "", showDetails);
    }
    public static string SerializeForUpdate(Event[] evs, string className, bool showDetails)
    {
        string retValue = "";
        if (evs == null)
            return retValue;
        for (int i = 0; i < evs.Length; i++)
        {
            Event e = (Event)evs.GetValue(i);
            if (e == null)
                continue;

            retValue += "<div class=\"text11 header1 " + className + "\"><table style=\"width:100%\"><tr><td style=\"align: right;\">" + Common.GetImageTextLink("ShowEvent.aspx?id=" + e.Id, "Images/dj/event.gif", StringHelper.RestrictMaxChar(e.Name, 15), 15) + "</td>";
            retValue += ((HttpContext.Current.Session["USERID"] != null && e.Organiser.UserID.ToLower() == HttpContext.Current.Session["USERID"].ToString().ToLower())
                ? "<td align=\"right\"><a href=\"" + ConfigurationManager.AppSettings["BaseUrl"] + "/UpdateShow.aspx?id=" + e.Id + "\" title=\"Edit\"><img alt=\"Edit\" style=\"width:15px;border:none;\" src=\"" + ConfigurationManager.AppSettings["BaseUrl"] + "/Images/dj/pen.gif\" /></a></td>"
                : "");
               retValue +=   "</tr></table></div><div class='text10' style=\"padding-left: 20px;\"><ul>";
            if (e.StartDate.CompareTo(Event.MinDate) != 1)
                retValue += "";
            else if (e.Status == EventStatus.Started)
                retValue += "<li><b>" + ResourceHelper.Get("LBL_StartedOn") + "</b> " + " <font class='greensig'><b>" + e.StartDate.ToShortDateString() + "</b></font></li>";
            else if (e.Status == EventStatus.Closed)
                retValue += "<li><b>" + "<font class='orangesig'>" + ResourceHelper.Get("LBL_Closed") + "</font><br/>";
            else
                retValue += "<li><b>" + ResourceHelper.Get("LBL_StartingOn") + "</b> " + " <font class='orangesig'>" + e.StartDate.ToShortDateString() + "</font></li>";
            if (e.FeeAmount > 0)
                retValue += "<li><b>" + ResourceHelper.Get("LBL_Fee") + "</b> " + " " + e.FeeAmount.ToString() + " " + Common.GetSettingValue(Collection.Currency, MathFunction.ConvertToInteger(e.Currency)) + "</li>";
            if (e.NominationStartDate.CompareTo(Event.MinDate) != 1)
                retValue += "";
            else if (e.NominationStatus == EventStatus.Started)
                retValue += "<li><b>" + ResourceHelper.Get("LBL_NStartedOn") + "</b> " + " <font class='greensig'><b>" + e.NominationStartDate.ToShortDateString() + "</b></font></li>";
            else if (e.NominationStatus == EventStatus.Closed)
                retValue += "<li><b>" + ResourceHelper.Get("LBL_Nomination") + "</b> " + " <font class='orangesig'>" + ResourceHelper.Get("LBL_Closed") + "</font></li>";
            else
                retValue += "<li><b>" + ResourceHelper.Get("LBL_NStartingOn") + "</b> " + " <font class='orangesig'>" + e.NominationStartDate.ToShortDateString() + "</font></li>";
            if (e.SponsorStartDate.CompareTo(Event.MinDate) != 1)
                retValue += "";
            else if (e.SponsorStatus == EventStatus.Started)
                retValue += "<li><b>" + ResourceHelper.Get("LBL_SStartedOn") + "</b> " + " <font class='greensig'><b>" + e.SponsorStartDate.ToShortDateString() + "</b></font></li>";
            else if (e.SponsorStatus == EventStatus.Closed)
                retValue += "<li><b>" + ResourceHelper.Get("LBL_Sponsorship") + "</b> " + " <font class='orangesig'>" + ResourceHelper.Get("LBL_Closed") + "</font></li>";
            else
                retValue += "<li><b>" + ResourceHelper.Get("LBL_SStartingOn") + "</b> " + " <font class='orangesig'>" + e.SponsorStartDate.ToShortDateString() + "</font></li>";
            if (showDetails)
            {
                retValue += "<li><b>" + ResourceHelper.Get("LBL_NominationsSubmitted") + "</b> " + e.Count.ToString() + "</li>";
                if (e.MaxNominationCount > 0 && e.MaxNominationCount >= e.Count)
                    retValue += "<li><b>" + ResourceHelper.Get("LBL_NominationsRemaining") + "</b> " + Convert.ToString(e.MaxNominationCount - e.Count) + "</li>";
                retValue += "<li><b>" + ResourceHelper.Get("LBL_VotesCount") + "</b> " + e.Votes.ToString() + "</li>";
                if (e.EndDate < Event.MaxDate)
                    retValue += "<li><b>" + ResourceHelper.Get("LBL_EventEndsOn") + "</b> " + e.EndDate.ToShortDateString() + "</li>";
                

            }
            retValue += "</ul></div>";
        }
        return retValue;
    }
    public static iControls_DashEntry CreateDashEntry(ref Page page, Entry entry, EntryMode mode)
    {
        iControls_DashEntry de = (iControls_DashEntry)page.LoadControl("~/Controls/DashEntry.ascx");
        DashEntry en = new DashEntry();
        en.Mode = mode;
        en.UserTextAlign = HorizontalAlign.Right;
        en.HeaderClass = "list_subheader";
        en.LiveHeaderClass = "list_subheader_live";
        en.SuspendHeaderClass = "list_subheader_suspend";
        SetDashEntry(ref de, en, 1);
        de.Entry = entry;
        de.OrderBy = Entry.GetOrderBy(Entry.GetOrderBy(0));
        //de.Height = Unit.Pixel(95);
        return de;
    }
    public static bool IsAdminSession
    {
        get
        {
            bool isAdmin = false;
            if (HttpContext.Current.Session["ISADMIN"] != null)
                bool.TryParse(HttpContext.Current.Session["ISADMIN"].ToString(), out isAdmin);
            return isAdmin;
        }
    }
}
